import { Ref, watch } from 'vue'
import { Viewer } from '../../../types'
import HotkeyRegister from './HotkeyRegister'
import { HotkeyType } from './useHotkey'

/** 缩放快捷键 */
export default function useZoom(register: HotkeyRegister, viewer: Viewer, viewerEl: Ref<HTMLElement | null>) {
  /** 缩放 100% */
  register.add({
    keys: '0',
    ctrlOrCmd: true,
    interval: 1000,
    handler: ({ e, viewer }) => {
      e.preventDefault()

      viewer.zoom.level = 1

      return false
    }
  })

  /** 缩放 +10% */
  register.add({
    keys: ['+', '='],
    type: HotkeyType.KEYDOWN,
    ctrlOrCmd: true,
    interval: 100,
    handler: ({ e, viewer }) => {
      e.preventDefault()

      viewer.zoom.level += 0.1

      return false
    }
  })

  /** 缩放 -10% */
  register.add({
    keys: '-',
    type: HotkeyType.KEYDOWN,
    ctrlOrCmd: true,
    interval: 100,
    handler: ({ e, viewer }) => {
      e.preventDefault()

      viewer.zoom.level -= 0.1
    }
  })

  /** 滚轮缩放 */
  function wheelZoom(e: WheelEvent) {
    // 按住 Ctrl 键
    if (!(e.ctrlKey || e.metaKey)) return

    e.preventDefault()

    viewer.zoom.level -= e.deltaY / 1000
  }

  /** 滚轮缩放 */
  watch(
    viewerEl,
    el => {
      if (!el) return

      el.removeEventListener('wheel', wheelZoom)
      el.addEventListener('wheel', wheelZoom)
    },
    { immediate: true }
  )
}
